<!DOCTYPE html>
<html>
<head>
    <title>动作课程新增</title>
    {% include 'admin/common/header.html' %}
    <style>
        .layui-form-item {
            margin-top: 17px !important;
            margin-bottom: 17px !important;
        }

        .layui-table-cell {
            height: 100px;
            line-height: 50px;
        }
    </style>
</head>
<body class="pear-container">
<div class="layui-row layui-col-space10">
    {# 左侧栏 #}
    <div class="layui-col-md3">
        {# 个人信息卡片 #}
        <div class="layui-card">
            <div class="layui-card-header">
                课程信息
            </div>
            <div class="layui-card-body" style="padding: 25px;">
                <div class="layui-form" action="">
                    <div class="layui-form-item">
                        <label class="layui-form-label">动作封面</label>
                        <div class="layui-input-block">
                            <div class="user-info-head" id="userInfoHead">
                                <img id="course_icon" src="{{ action.icon_path }}" width="115px"
                                     height="115px" alt="">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">动作名称</label>
                        <div class="layui-input-block">
                            <input type="text" id="course_name" lay-verify="required" placeholder="请输入课程名称"
                                   autocomplete="off" class="layui-input" value="{{ action.action_name }}">
                        </div>
                    </div>
                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">动作介绍</label>
                        <div class="layui-input-block">
                            <textarea id="course_description" placeholder="请输入动作详细信息" class="layui-textarea"
                                      rows=17>{{ action.action_description }}</textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
    {# 右侧栏 #}
    <div class="layui-col-md9">
        <div class="layui-card">
            <div class="layui-card-header">视频与关键点选择</div>
            <div class="layui-card-body">
                <form class="layui-form layui-row layui-col-space12">
                    <div class="layui-form-item">
                        <label class="layui-form-label">视频选择</label>
                        <div class="layui-input-block">
                            <div class="pear-btn pear-btn-primary" id="btn_select_video">点击选择本地视频
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">视频</label>
                        <div class="layui-input-block">
                            <input type="file" id="input_video" accept="video/*" style="display: none;">
                            <video id="video" controls style="width: 600px;" src="{{ action.action_path }}"></video>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">智能生成</label>
                        <div class="layui-input-block">
                            <div class="layui-btn layui-btn-primary layui-border-green" id="btn_auto_generate">
                                智能生成关键帧
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md12">
                        <label class="layui-form-label">时间设置</label>
                        <div class="layui-input-inline">
                            <div class="pear-btn pear-btn-primary" id="btn_set_start">设置当前为关键点开始时间
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <div class="layui-input-block" style="margin-top: 0;text-align: left;">

                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <div class="layui-input-block" style="margin-top: 0;">

                            </div>
                        </div>
                    </div>
                </form>

            </div>
        </div>


    </div>
    <div class="layui-col-md12">
        <div class="layui-card">
            <div class="layui-card-header">视频关键点选择</div>
            <div class="layui-card-body">
                <div class="layui-form layui-row layui-col-space12">
                    <div class="layui-col-md12">
                        <div class="layui-form-item" style="margin-bottom: 0;">
                            <label class="layui-form-label">开始时间</label>
                            <div class="layui-input-inline" style="max-width: 55%">
                                <input type="text" class="layui-input" id="keypoint-start"
                                       placeholder="时分秒">
                            </div>
                            <div class="layui-input-inline" style="max-width: 1px;margin-bottom: 0;">
                                <h3>:</h3>
                            </div>
                            <div class="layui-input-inline" style="max-width: 20%">
                                <input type="number" class="layui-input" id="milliseconds-start" min="0" max="999"
                                       step="1" placeholder="毫秒" style="max-width: 100px">
                            </div>
                            <div class="layui-input-inline" style="margin-bottom: 0;">
                                <div class="pear-btn pear-btn-primary" id="btn_jump_start">跳转
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md12">
                        <div class="layui-input-inline layui-col-md2">
                            <label class="layui-form-label" style="text-align: left;margin-left: 25px">动作要点</label>
                        </div>
                        <div class="layui-col-md2">
                            <div class="layui-input-inline layui-col-space12">
                                <div class="layui-col-md6">
                                    <label class="layui-form-label" style="text-align: left;">左肩</label>
                                </div>
                                <div class="layui-col-md6" style="text-align: left;">
                                    <input type="checkbox" class="keypoint-select" id="left-shoulder" lay-skin="switch"
                                           lay-text="启用|禁用"
                                           lay-filter="user-enable"/>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md2">
                            <div class="layui-input-inline layui-col-space12">
                                <div class="layui-col-md6">
                                    <label class="layui-form-label" style="text-align: left;">左肘</label>
                                </div>
                                <div class="layui-col-md6" style="text-align: left;">
                                    <input type="checkbox" class="keypoint-select" id="left-elbow" lay-skin="switch"
                                           lay-text="启用|禁用"
                                           lay-filter="user-enable"/>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md2">
                            <div class="layui-input-inline layui-col-space12">
                                <div class="layui-col-md6">
                                    <label class="layui-form-label" style="text-align: left;">左腕</label>
                                </div>
                                <div class="layui-col-md6" style="text-align: left;">
                                    <input type="checkbox" class="keypoint-select" id="left-wrist" lay-skin="switch"
                                           lay-text="启用|禁用"
                                           lay-filter="user-enable"/>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md2">
                            <div class="layui-input-inline layui-col-space12">
                                <div class="layui-col-md6">
                                    <label class="layui-form-label" style="text-align: left;">左脚</label>
                                </div>
                                <div class="layui-col-md6" style="text-align: left;">
                                    <input type="checkbox" class="keypoint-select" id="left-foot" lay-skin="switch"
                                           lay-text="启用|禁用"
                                           lay-filter="user-enable"/>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md2">
                            <div class="layui-input-inline layui-col-space12">
                                <div class="layui-col-md6">
                                    <label class="layui-form-label" style="text-align: left;">左膝</label>
                                </div>
                                <div class="layui-col-md6" style="text-align: left;">
                                    <input type="checkbox" class="keypoint-select" id="left-knee" lay-skin="switch"
                                           lay-text="启用|禁用"
                                           lay-filter="user-enable"/>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="layui-col-md12">
                        <div class="layui-input-inline layui-col-md2">
                            <label class="layui-form-label" style="text-align: left;margin-left: 25px"></label>
                        </div>
                        <div class="layui-col-md2">
                            <div class="layui-input-inline layui-col-space12">
                                <div class="layui-col-md6">
                                    <label class="layui-form-label" style="text-align: left;">右肩</label>
                                </div>
                                <div class="layui-col-md6" style="text-align: left;">
                                    <input type="checkbox" class="keypoint-select" id="right-shoulder" lay-skin="switch"
                                           lay-text="启用|禁用"
                                           lay-filter="user-enable"/>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md2">
                            <div class="layui-input-inline layui-col-space12">
                                <div class="layui-col-md6">
                                    <label class="layui-form-label" style="text-align: left;">右肘</label>
                                </div>
                                <div class="layui-col-md6" style="text-align: left;">
                                    <input type="checkbox" class="keypoint-select" id="right-elbow" lay-skin="switch"
                                           lay-text="启用|禁用"
                                           lay-filter="user-enable"/>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md2">
                            <div class="layui-input-inline layui-col-space12">
                                <div class="layui-col-md6">
                                    <label class="layui-form-label" style="text-align: left;">右腕</label>
                                </div>
                                <div class="layui-col-md6" style="text-align: left;">
                                    <input type="checkbox" class="keypoint-select" id="right-wrist" lay-skin="switch"
                                           lay-text="启用|禁用"
                                           lay-filter="user-enable"/>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md2">
                            <div class="layui-input-inline layui-col-space12">
                                <div class="layui-col-md6">
                                    <label class="layui-form-label" style="text-align: left;">右脚</label>
                                </div>
                                <div class="layui-col-md6" style="text-align: left;">
                                    <input type="checkbox" class="keypoint-select" id="right-foot" lay-skin="switch"
                                           lay-text="启用|禁用"
                                           lay-filter="user-enable"/>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md2">
                            <div class="layui-input-inline layui-col-space12">
                                <div class="layui-col-md6">
                                    <label class="layui-form-label" style="text-align: left;">右膝</label>
                                </div>
                                <div class="layui-col-md6" style="text-align: left;">
                                    <input type="checkbox" class="keypoint-select" id="right-knee" lay-skin="switch"
                                           lay-text="启用|禁用"
                                           lay-filter="user-enable"/>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md12">
                        <div class="layui-form-item" style="margin-bottom: 0;">
                            <label class="layui-form-label">描述</label>
                            <div class="layui-input-block">
                            <textarea id="keyframe_description" placeholder="关键帧描述" class="layui-textarea"
                                      rows=5></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item" style="margin-bottom: 0;text-align: right;margin-right: 20px;">
                        <div class="pear-btn pear-btn-primary" id="btn_add_point">新增关键点
                        </div>
                    </div>
                    <div class="layui-form-item" style="margin-bottom: 0;text-align: right;margin-right: 20px;">
                        <table id="user-table" lay-filter="user-table"></table>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-card">
            <div class="layui-card-body" style="text-align: right">
                <div class="layui-btn layui-btn-primary layui-border-green" id="submit_course"><i
                        class="layui-icon layui-icon-ok"></i>提交
                </div>
                <div class="layui-btn layui-btn-primary layui-border-red" id="cancel_course"><i
                        class="layui-icon layui-icon-close"></i>取消
                </div>
            </div>
        </div>
    </div>
</div>
</div>
{% include 'admin/common/footer.html' %}


<script type="text/html" id="user-bar">
    <button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove">
        <i class="pear-icon pear-icon-ashbin"></i>
    </button>
</script>

<script>

    layui.use(['table', 'dropdown', 'dtree', 'form', 'jquery', 'popup', 'common'], function () {
            let $ = layui.jquery
            let layer = layui.layer
            let form = layui.form
            let popup = layui.popup
            let table = layui.table
            let laydate = layui.laydate;
            let MODULE_PATH = '/course/standard/'
            let data = []
            let file
            let keyframes
            let videoPath = ''
            let videoDuration = 0.0
            let skeletonList
            let deleteList
            let action_id
            {% for keyframe in keyframes %}
                var bools = binToBools({{ keyframe.keyframe_focus }})
                action_id = parseInt({{ keyframe.action_id }})
                data.push({
                    action_id: parseInt({{ keyframe.action_id }}),
                    keyframe_id: parseInt({{ keyframe.keyframe }}),
                    keyframe_description: "{{ keyframe.keyframe_description }}",
                    start: "{{ keyframe.start }}",
                    startMills: parseInt({{ keyframe.startMills }}),
                    keyframe_focus: {
                        'left-shoulder': bools[0],
                        'left-elbow': bools[1],
                        'left-wrist': bools[2],
                        'left-foot': bools[3],
                        'left-knee': bools[4],
                        'right-shoulder': bools[5],
                        'right-elbow': bools[6],
                        'right-wrist': bools[7],
                        'right-foot': bools[8],
                        'right-knee': bools[9]
                    }
                })
            {% endfor %}
            console.log(data)
            // 修改课程图标
            $('#course_icon').click(function () {
                layer.open({
                    type: 2,
                    title: '更换图片',
                    shade: 0.1,
                    area: ['900px', '500px'],
                    content: MODULE_PATH + 'cover',
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {
                        window['layui-layer-iframe' + index].submitForm()
                    }
                })
            })
            {#
                视频相关事件
            #}

            // 设置选择本地视频
            $('#btn_select_video').click(function () {
                $('#input_video').click()
            })
            $('#input_video').change(function (event) {
                file = event.target.files[0];
                var url = URL.createObjectURL(file);
                $('#video').attr('src', url)
            })

            // 加载完成视频后异步获取视频的时长等信息
            $('#video').on('loadedmetadata', function () {
                // 获取视频时长
                videoDuration = $('video').prop('duration')
                // 本地视频选择后设置关键点选择相关选项为可用
                $('#keypoint-start').prop('disabled', false)
                $('#milliseconds-start').prop('disabled', false)
                $('#action-select').prop('disabled', false)
                // 设置可选择时间范围
                var endTime = secondToHours(videoDuration)
                laydate.render({
                    elem: '#keypoint-start',
                    type: 'time',
                    // 设置最小时间为0，最大时间为视频时间长度
                    min: '00:00:00',
                    max: endTime,
                    btns: ['clear', 'confirm'],
                    change: function (value) {
                        $('#milliseconds-start').val("000")
                    }
                });
            })

            // 视频暂停时，如果开始时间和结束时间为空，会更新开始时间和结束时间
            $('#video').on('pause', function () {
                var currentTime = $('#video').prop('currentTime')
                if ($('#keypoint-start').prop('value') === '') {
                    $('#keypoint-start').prop('value', secondToHours(currentTime))
                }
            })
            // 点击设置当前为关键点开始时间按钮的时间处理
            $('#btn_set_start').click(function () {
                if ($('#video').attr('src') === undefined) {
                    popup.failure('请选择视频')
                    return
                }
                // 设置视频当前时间为视频关键点开始时间
                var currentTime = $('#video').prop('currentTime')
                $('#keypoint-start').val(secondToHours(currentTime))
                $('#milliseconds-start').val(fillZero(parseInt(currentTime % 1 * 1000)))
            })


            {#把秒转化为HH:mm:ss格式#}

            function secondToHours(seconds) {
                var date = new Date(null);
                date.setSeconds(seconds);
                var timeString = date.toISOString().substr(11, 8);
                return timeString;
            }

            {#把HH:mm:ss转化为秒#}

            function hoursToSeconds(timeString) {
                var timeParts = timeString.split(':');
                var hours = parseInt(timeParts[0]);
                var minutes = parseInt(timeParts[1]);
                var seconds = parseInt(timeParts[2]);
                var totalSeconds = hours * 3600 + minutes * 60 + seconds;
                return totalSeconds;
            }

            function fillZero(ms) {
                if (ms < 0) {
                    return "000"
                }
                if (ms >= 1000) {
                    return "999"
                }
                if (ms < 10) {
                    return "00" + ms
                }
                if (ms < 100) {
                    return "0" + ms
                }
                return String(ms)
            }

            $('#milliseconds-start').change(function () {
                if ($('#keypoint-start').val() == '') {
                    $('#keypoint-start').val('00:00:00')
                }
                this.value = fillZero(parseInt(this.value))
            })


            {#
                实现关键点选择
            #}
            // 视频开始时间跳转
            $('#btn_jump_start').click(function () {
                if ($('#keypoint-start').val() === '') {
                    popup.failure('请输入开始时间');
                } else {
                    var currentTime = hoursToSeconds($('#keypoint-start').val()) + parseInt($('#milliseconds-start').val()) / 1000.0
                    $('#video').prop('currentTime', currentTime)
                }
            })

            // 实现把数字转化为十个布尔值
            function binToBools(binNum) {
                // 确保输入的是 10 位二进制数
                if (binNum > 1023 || binNum < 0) {
                    throw new Error("Input number must be a 10-bit binary number");
                }
                let binStr = binNum.toString(2).padStart(10, '0');
                return binStr.split('').map(b => Boolean(parseInt(b)));
            }

            {#
                点击新增关键点后的处理方法
            #}
            $('#btn_add_point').click(function () {
                    var action = ''
                    var actionDict = {
                        id: data.length,
                        start: $('#keypoint-start').val(),
                        startMills: $('#milliseconds-start').val(),
                        keyframe_description: $('#keyframe_description').val(),
                        keyframe_focus: {}
                    }
                    $(".keypoint-select").each(function () {

                        actionDict["keyframe_focus"][$(this).prop('id')] = $(this).is(':checked');
                        if ($(this).is(':checked')) {
                            action += $(this).parent().prev().text();
                            +';'
                        }

                    });
                    actionDict.action = action
                    // 所有关键点数据都存在data中，在data中插入新数据
                    data.push(actionDict)
                    // 向data中插入新数据后，更新表格
                    table.reload('user-table', {
                        data: data
                    })
                    $('#keypoint-start').val('')
                    $('#milliseconds-start').val('')
                    $('#keyframe_description').val('')

                }
            )
            // 表格数据
            let cols = [
                [
                    {
                        title: '关键点开始时间',
                        field: 'keypoint_start',
                        align: 'center',
                        templet: function (d) {
                            var htmlString = '<div class="layui-input-inline" style="max-width: 50%;">' +
                                '        <input type="text" class="layui-input layui-keypoint-start" id="id_keypoint_start_' + d.id + '" value="' + d.start + '" placeholder="时分秒">' +
                                '    </div>' +
                                '    <div class="layui-input-inline" style="max-width: 25%">' +
                                '        <input type="number" class="layui-input millisecond-start" id="id_milliseconds_start_' + d.id + '" value="' + d.startMills + '" min="0" max="999" step="1" placeholder="毫秒">' +
                                '    </div>'
                            return htmlString
                        },
                        width: 230
                    },
                    {
                        title: '动作要点',
                        field: 'action',
                        align: 'center',
                        templet: function (d) {
                            var htmlString = ''
                            if (d['keyframe_focus']['left-shoulder']) {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="left-shoulder" id="id_left_shoulder_' + d.id + '" title="左肩" lay-skin="tag" lay-filter="keyframe-filter" checked>'
                            } else {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="left-shoulder" id="id_left_shoulder_' + d.id + '" title="左肩" lay-filter="keyframe-filter" lay-skin="tag">'
                            }
                            if (d['keyframe_focus']['left-elbow']) {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="left-elbow" id="id_left_elbow_' + d.id + '" title="左肘" lay-skin="tag" lay-filter="keyframe-filter" checked>'
                            } else {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="left-elbow" id="id_left_elbow_' + d.id + '" title="左肘" lay-skin="tag" lay-filter="keyframe-filter">'
                            }
                            if (d['keyframe_focus']['left-wrist']) {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="left-wrist" id="id_left_wrist_' + d.id + '" title="左腕" lay-skin="tag" lay-filter="keyframe-filter" checked>'
                            } else {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="left-wrist" id="id_left_wrist_' + d.id + '" title="左腕" lay-skin="tag" lay-filter="keyframe-filter">'
                            }
                            if (d['keyframe_focus']['left-foot']) {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="left-foot" id="id_left_foot_' + d.id + '" title="左脚" lay-skin="tag" lay-filter="keyframe-filter" checked>'
                            } else {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="left-foot" id="id_left_foot_' + d.id + '" title="左脚" lay-skin="tag" lay-filter="keyframe-filter">'
                            }
                            if (d['keyframe_focus']['left-knee']) {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="left-knee" id="id_left_knee_' + d.id + '" title="左膝" lay-skin="tag" lay-filter="keyframe-filter" checked>'
                            } else {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="left-knee" id="id_left_knee_' + d.id + '" title="左膝" lay-skin="tag" lay-filter="keyframe-filter">'
                            }
                            htmlString += '<br/>'
                            if (d['keyframe_focus']['right-shoulder']) {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="right-shoulder" id="id_right_shoulder_' + d.id + '" title="右肩" lay-skin="tag" lay-filter="keyframe-filter" checked >'
                            } else {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="right-shoulder" id="id_right_shoulder_' + d.id + '" title="右肩" lay-skin="tag" lay-filter="keyframe-filter">'
                            }
                            if (d['keyframe_focus']['right-elbow']) {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="right-elbow" id="id_right_elbow_' + d.id + '" title="右肘" lay-skin="tag" lay-filter="keyframe-filter" checked>'
                            } else {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="right-elbow" id="id_right_elbow_' + d.id + '" title="右肘" lay-skin="tag" lay-filter="keyframe-filter">'
                            }
                            if (d['keyframe_focus']['right-wrist']) {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="right-wrist" id="id_right_wrist_' + d.id + '" title="右腕" lay-skin="tag" lay-filter="keyframe-filter" checked>'
                            } else {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="right-wrist" id="id_right_wrist_' + d.id + '" title="右腕" lay-skin="tag" lay-filter="keyframe-filter">'
                            }
                            if (d['keyframe_focus']['right-foot']) {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="right-foot" id="id_right_foot_' + d.id + '" title="右脚" lay-skin="tag" lay-filter="keyframe-filter" checked>'
                            } else {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="right-foot" id="id_right_foot_' + d.id + '" title="右脚" lay-skin="tag" lay-filter="keyframe-filter">'
                            }
                            if (d['keyframe_focus']['right-knee']) {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="right-knee" id="id_right_knee_' + d.id + '" title="右膝" lay-skin="tag" lay-filter="keyframe-filter" checked>'
                            } else {
                                htmlString += '<input type="checkbox" class="keypoint-list-select" name="right-knee" id="id_right_knee_' + d.id + '" title="右膝" lay-skin="tag" lay-filter="keyframe-filter">'
                            }
                            return htmlString
                        }
                    },
                    {
                        title: '描述',
                        field: 'keyframe_description',
                        align: 'center',
                        width: 400,
                        templet: function (d) {
                            var htmlString = '<textarea id="id_keyframe_description_' + d.id + '" placeholder="请输入动作详细描述" class="layui-textarea keyframe-textarea" rows=3>' + d.keyframe_description + '</textarea>'
                            return htmlString
                        }
                    },
                    {
                        title: '操作',
                        toolbar: '#user-bar',
                        align: 'center',
                        width: 130
                    }
                ]
            ]
            // 获取动作的选项
            let dataAction = [];
            $('#action-select option').each(function () {
                var titleAction = $(this).text();
                var idAction = $(this).val();
                dataAction.push({
                    title: titleAction,
                    id: idAction
                });
            });

            // 智能生成关键帧按钮点击事件
            $('#btn_auto_generate').click(function () {
                if (!file) {
                    popup.failure('请选择视频')
                    return
                }
                if (videoDuration > 5 * 60) {
                    popup.failure('智能生成关键帧的视频长度不能超过五分钟')
                }
                // 设置视频跨域
                $('#video').crossOrigin = 'anonymous'
                // 获取文件名称
                var filePath = file.name
                // 获取文件后缀(文件类型)
                var index = filePath.lastIndexOf(".");
                var ext = filePath.substring(index);
                // 用当前时间重命名文件,防止文件名称冲突
                let timeStamp = Date.parse(new Date())
                let fileName = timeStamp + ext
                // 设置文件信息
                let formData = new FormData()
                formData.append('file', file, fileName)
                formData.append('fileName', fileName)
                formData.append('fileToken', timeStamp)
                // 弹出等待窗口
                var index = layer.load(0, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });

                layer.msg("视频正在上传中，请耐心等待")

                // 先上传视频,上传成功的话,请求为视频url生成关键帧
                $.ajax({
                    method: 'post',
                    url: '/admin/file/videos/upload', //用于文件上传的服务器端请求地址
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (result) {
                        if (result.success) {
                            layer.msg("开始智能生成关键帧，请耐心等候")
                            videoPath = result.data.src
                            $.ajax({
                                method: 'post',
                                url: MODULE_PATH + 'generate',
                                data: JSON.stringify({
                                    path: result.data.src
                                }),
                                contentType: 'application/json',
                                success: function (result) {
                                    layer.close(index)
                                    popup.success(result.msg)
                                    keyframes = JSON.parse(result.data.keyframe_info);
                                    $('#course_icon').attr('src', result.data.icon_path)
                                    skeletonList = result.data.skeleton_list
                                    for (var key in keyframes) {
                                        var actionDict = {
                                            id: data.length,
                                            start: secondToHours(parseInt(key) / 1000),
                                            startMills: parseInt(key) % 1000,
                                            keyframe_description: '',
                                            keyframe_focus: {},
                                        }
                                        $(".keypoint-select").each(function () {
                                            actionDict["keyframe_focus"][$(this).prop('id')] = true;
                                        });
                                        var value = keyframes[key]; // 根据键获取值
                                        actionDict['skeleton'] = value[2];
                                        data.push(actionDict)
                                    }
                                    table.reload('user-table', {
                                        data: data
                                    })
                                }
                            })
                        } else {
                            layer.close(index)
                            popup.failure(result.msg)
                        }
                    }
                })

            })

            // 渲染表格数据
            table.render({
                elem: '#user-table',
                cols: cols,
                skin: 'line',
                page: true,
                limits: 10,
                data: data,
                // 表格加载完成后操作
                done: function (res, curr, count) {
                    var options = this;
                    // 根据点击的按钮获取按钮所在行的数据
                    table.getRowData = function (elem) {
                        var index = $(elem).closest('tr').data('index');
                        return table.cache[options.id][index] || {};
                    };

                    // 渲染表格每行的开始时间输入框
                    $('.layui-keypoint-start').each(function () {
                        laydate.render({
                            elem: this,
                            type: 'time',
                            min: '00:00:00',
                            max: '17:30:00',
                            btns: ['clear', 'confirm'],
                            // 如果开始时间输入框内的数据发生变化执行以下操作
                            done: function (value, date, endDate) {
                                // 获取操作所在行的数据
                                var rowData = table.getRowData(this.elem);
                                // 找到data中对应的数据进行更新
                                for (var i = 0; i < data.length; i++) {
                                    if (data[i].id === rowData.id) {
                                        data[i].start = value
                                    }
                                }
                            }
                        });
                    })

                    // 毫秒输入框变化时，改变data数据
                    $('.millisecond-start').change(function () {
                        var rowData = table.getRowData(this);
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].id === rowData.id) {
                                data[i].startMills = this.value
                            }
                        }
                    })

                    // 列表中动作要点的点击事件
                    form.on('checkbox(keyframe-filter)', function (obj) {
                        // 检查复选框的状态
                        var rowData = table.getRowData(obj.elem)
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].id == rowData.id) {
                                data[i]['keyframe_focus'][obj.elem.name] = obj.elem.checked
                                break;
                            }
                        }
                    });
                    $('.keyframe-textarea').change(function () {
                        var rowData = table.getRowData(this)
                        rowData.keyframe_description = this.value
                    })
                },
            })

            // 提交数据
            $('#submit_course').click(function () {
                var course_icon = $('#course_icon').attr('src')
                var course_name = $('#course_name').val()
                if (course_name == '') {
                    popup.failure('请输入课程名称')
                    return
                }

                var course_description = $('#course_description').val()
                if (videoPath != '') {
                    // 设置视频跨域
                    $('#video').crossOrigin = 'anonymous'
                    // 获取文件名称
                    var filePath = file.name
                    // 获取文件后缀(文件类型)
                    var index = filePath.lastIndexOf(".");
                    var ext = filePath.substring(index);
                    // 用当前时间重命名文件,防止文件名称冲突
                    let timeStamp = Date.parse(new Date())
                    let fileName = timeStamp + ext
                    // 设置文件信息
                    let formData = new FormData()
                    formData.append('file', file, fileName)
                    formData.append('fileName', fileName)
                    formData.append('fileToken', timeStamp)
                    // 弹出等待窗口
                    var index = layer.load(0, {
                        shade: [0.1, '#fff'] //0.1透明度的白色背景
                    });
                    layer.msg("正在上传视频中，请耐心等待……")
                    // 先上传视频,上传成功的话,上传课程信息,上传课程信息成功后,上传关键帧信息
                    $.ajax({
                        method: 'POST',
                        url: '/admin/file/videos/upload', //用于文件上传的服务器端请求地址
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (result) {
                            if (result.success) {
                                videoPath = result.data.src
                                layer.msg("正在为视频生成骨架，请耐心等待……")
                                $.ajax({
                                    method: 'POST',
                                    url: MODULE_PATH + 'generate',
                                    data: JSON.stringify({
                                        path: result.data.src
                                    }),
                                    contentType: 'application/json',
                                    success: function (result) {
                                        if (result.success) {
                                            skeletonList = result.data.skeleton_list
                                            $('#course_icon').prop('src', result.data.icon_path)
                                            var actionInfo = {
                                                action_id: action_id,
                                                action_name: course_name,
                                                action_icon: $('#course_icon').attr('src'),
                                                action_description: course_description,
                                                action_path: videoPath,
                                                action_length: parseInt(videoDuration * 1000),
                                                skeleton_list: skeletonList,
                                                delete_list: deleteList,
                                                keyframes: data
                                            }
                                            layer.close(index)
                                            for (var d in window.parent.data) {
                                                if (d.action_id == action_id) {
                                                    d = actionInfo
                                                    break
                                                }
                                            }
                                            popup.success("动作编辑成功")
                                            setTimeout(function () {
                                                parent.layui.table.reload('user-table')
                                                parent.layer.close(parent.layer.getFrameIndex(window.name))
                                            }, 1000)
                                        } else {
                                            popup.failure(result.msg)
                                            layer.close(index)
                                        }
                                    }
                                })

                            } else {
                                popup.failure(result.msg)
                                layer.close(index)
                            }
                        }
                    })
                } else {
                    videoPath = $('#video').prop('src')
                    layer.msg("正在为视频生成骨架，请耐心等待……")
                    $.ajax({
                        method: 'POST',
                        url: MODULE_PATH + 'generate',
                        data: JSON.stringify({
                            path: videoPath
                        }),
                        contentType: 'application/json',
                        success: function (result) {
                            skeletonList = result.data.skeleton_list
                            console.log(skeletonList)
                            var actionInfo = {
                                id: window.parent.data.length,
                                action_id: action_id,
                                action_name: course_name,
                                action_icon: $('#course_icon').attr('src'),
                                action_description: course_description,
                                action_path: videoPath,
                                action_length: parseInt(videoDuration * 1000),
                                skeleton_list: skeletonList,
                                keyframes: data
                            }
                            layer.close(index)
                            for (var d in window.parent.data) {
                                if (d.action_id == action_id) {
                                    d = actionInfo
                                    break
                                }
                            }
                            popup.success("动作编辑成功")
                            setTimeout(function () {
                                parent.layui.table.reload('user-table')
                                parent.layer.close(parent.layer.getFrameIndex(window.name))
                            }, 1000)
                        }
                    })

                }
            })
            $('#cancel_course').click(function () {
                parent.layer.close(parent.layer.getFrameIndex(window.name))
            })
            //
            $('.user-group').click(function () {
                let group = $(this).attr('user-group')
                let field = form.val('user-query-form')
                if (group === '-1') {
                    field.deptId = group
                    $(this).removeClass('button-default')
                    $(this).prev().removeClass('button-primary')
                    $(this).prev().addClass('button-default')
                    $(this).addClass('button-primary')
                } else {
                    field.deptId = group
                    $(this).removeClass('button-default')
                    $(this).next().removeClass('button-primary')
                    $(this).next().addClass('button-default')
                    $(this).addClass('button-primary')
                }
                window.refresh(field)
            })

            table.on('tool(user-table)', function (obj) {
                if (obj.event === 'remove') {
                    window.remove(obj)
                }
            })

            window.remove = function (obj) {
                layer.confirm('确定要删除该关键点', {icon: 3, title: '提示'}, function (index) {
                    layer.close(index)
                    // 删除时，除了删除表格中的数据，也要删除data中的数据
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].id === obj.data.id) {
                            data.splice(i, 1)
                            deleteList.push(data[i].keyframe_id)
                            break
                        }
                    }
                    popup.success("删除成功", function () {
                        obj.del()
                    })
                })
            }
        }
    )
</script>
</body>
</html>
